package tw.com.hitevision.whiteboard.android.widgets;

import android.content.Context;
import android.util.Log;

import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.model.service.GetServiceRequest;
import com.tencent.cos.xml.model.service.GetServiceResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.transfer.TransferStateListener;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider;

import java.io.File;

import tw.com.hitevision.whiteboard.android.R;
import tw.com.hitevision.whiteboard.android.util.HttpShareUtils;

public class TenCentCloud {
    private static final String TAG = TenCentCloud.class.getSimpleName();
    private static final String SECRET_ID = "AKIDEQQFuR92Cey79IfTQCnDSY2TjPwJrUIx";
    private static final String SECRET_KEY = "fEjO1YyFuwTHKRhqpiQm3A6vZ1oSI1gi";

    private static TenCentCloud instance;
    private CosXmlService cosXmlService;
    private TransferManager transferManager;
    private final String rootDir;
    private final String bucket;
    private final String region;

    private TenCentCloudCallBack listener;

    public static TenCentCloud getInstance(Context context) {
        if (instance == null) {
            instance = new TenCentCloud(context);
        }

        return instance;
    }

    private TenCentCloud(Context context) {
        region = context.getResources().getString(R.string.tenscent_cloud_region_name);

        String appId = context.getResources().getString(R.string.tencent_cloud_bucket_appid);

        CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
                .setRegion(region)
                .isHttps(true)
                .setDebuggable(true)
                .builder();

        QCloudCredentialProvider credentialProvider = new ShortTimeCredentialProvider(SECRET_ID, SECRET_KEY, 600);

        cosXmlService = new CosXmlService(context, serviceConfig, credentialProvider);

        rootDir = context.getResources().getString(R.string.tenscent_cloud_root_dir);

        bucket = context.getResources().getString(R.string.tencent_cloud_bucket_name) + "-" + appId;

//        PutBucketRequest putBucketRequest = new PutBucketRequest(bucket);

//        cosXmlService.putBucketAsync(putBucketRequest, new CosXmlResultListener() {
//            @Override
//            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
//                // todo Put Bucket success
//                PutBucketResult putBucketResult = (PutBucketResult) result;
//            }
//
//            @Override
//            public void onFail(CosXmlRequest cosXmlRequest, CosXmlClientException clientException, CosXmlServiceException serviceException) {
//                // todo Put Bucket failed because of CosXmlClientException or CosXmlServiceException...
//            }
//        });

        GetServiceRequest getServiceRequest = new GetServiceRequest();
        cosXmlService.getServiceAsync(getServiceRequest, new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                // todo Put Bucket Lifecycle success
                GetServiceResult getServiceResult = (GetServiceResult) result;
                log("GetServiceResult : " + (getServiceResult != null ? getServiceResult.printResult() : "null"));
            }

            @Override
            public void onFail(CosXmlRequest cosXmlRequest, CosXmlClientException clientException, CosXmlServiceException serviceException) {
                // todo Put Bucket Lifecycle failed because of CosXmlClientException or CosXmlServiceException...
//                log("GetServiceRequest failed... clientException : " + (clientException != null ? clientException.errorMessage : "null") +
//                        ", serviceException : " + (serviceException != null ? serviceException.getMessage() : "null"));
            }
        });

        // upload manager
        TransferConfig transferConfig = new TransferConfig.Builder().build();

        transferManager = new TransferManager(cosXmlService, transferConfig);

    }

    public void upload(String fileName, String filepath, String fileFolder, boolean end, int pages) {
        String cosPath = rootDir + File.separator + fileFolder + File.separator + fileName; //即对象到 COS 上的绝对路径, 格式如 cosPath = "text.txt";
        String srcPath = filepath; // 如 srcPath=Environment.getExternalStorageDirectory().getPath() + "/text.txt";
        String uploadId = null; //若存在初始化分片上传的 UploadId，则赋值对应 uploadId 值用于续传，否则，赋值 null。

        //上传对象
        COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath, srcPath, uploadId);

        if (listener != null) {
            // open qrcode view first
            listener.onFinish(null);
        }

//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, srcPath);
//        putObjectRequest.setRegion(region);
//        putObjectRequest.setSign(600);
//        putObjectRequest.setNeedMD5(true);
//        COSXMLUploadTask cosxmlUploadTask = transferManager.upload(putObjectRequest, null);

        //设置上传进度回调
        cosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(long complete, long target) {
                float progress = 1.0f * complete / target * 100;
//                Log.d("TEST",  String.format("progress = %d%%", (int)progress));
                log("Progress : " + progress);
            }
        });

        //设置返回结果回调
        cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult = (COSXMLUploadTask.COSXMLUploadTaskResult) result;
//                Log.d("TEST",  "Success: " + cOSXMLUploadTaskResult.printResult());
                log("Upload success : " + cOSXMLUploadTaskResult.printResult());

//                String method = "GET"; //请求HTTP方法，如下载 GET, PUT 上传.
//                PresignedUrlRequest presignedUrlRequest = new PresignedUrlRequest(bucket, cosPath);
//                presignedUrlRequest.setRequestMethod(method);
//                String url = cosXmlService.getAccessUrl(presignedUrlRequest);
//
//                if (listener != null) {
//                    listener.onFinish(url);
//                }

                if (end) {
                    String url = HttpShareUtils.httpRequest(fileFolder, pages);
                    log("Url : " + url);
                    if (listener != null) {
                        listener.onFinish(url);
                    }
                }

            }

            @Override
            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                log("Upload Failed: " + (exception == null ? serviceException.getMessage() : exception.toString()));
            }
        });

        //设置任务状态回调, 可以查看任务过程
        cosxmlUploadTask.setTransferStateListener(new TransferStateListener() {
            @Override
            public void onStateChanged(TransferState state) {
                log("Upload state:" + state.name());
            }
        });

//        //取消上传
//        cosxmlUploadTask.cancel();
//
//        //暂停上传
//        cosxmlUploadTask.pause();
//
//        //恢复上传
//        cosxmlUploadTask.resume();


    }

    public void setListener(TenCentCloudCallBack listener) {
        this.listener = listener;
    }

    public interface TenCentCloudCallBack {
        void onFinish(String url);
    }

    private void log(String s) {
        Log.d(TAG, s);
    }
}
